package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.OcrUtil;
import com.heima.utils.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.invoke.LambdaConversionException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AutoScanServiceImpl implements AutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private IArticleClient iArticleClient;

    @Autowired
    private WmChannelService wmChannelService;

    @Autowired
    private WmUserService wmUserService;

    @Override
    @Async   //加此注解之后此方法异步调用 作为一个子线程运行
    public void autoScanWmNews(Long newsId) throws Exception {
        // 0.判空
        if (newsId == null) {
            log.warn("newsId为空");
            return;
        }
        // 1.查询新闻信息
        WmNews wmNews = wmNewsMapper.selectById(newsId);
        if (wmNews == null) {
            log.warn("新闻" + newsId + "为空");
            return;
        }
        // 2.提取新闻文字
        String title = wmNews.getTitle();
        String content = wmNews.getContent();
        String text = getText(title, content);
        // 3.提取新闻图片
        String images = wmNews.getImages();
        List<byte[]> imageList = getImages(images, content);

        //通过ocr处理图片中的文字
        String textFromOcr = ocrCheck(imageList);
        text = text + "_" +textFromOcr;

        //todo  使用DFA算法处理敏感词
        Boolean dfaResult = dfaCheck(text);
        if (!dfaResult) {
            //检测未通过,更新文章状态
            updateWmNews(2, "DFA审核未通过", null, newsId.intValue());
        }
        //todo map为空 4.调用文字审核接口
        Map map = greenTextScan.greeTextScan(text);
        Boolean textScanResult = checkResult(map, null, newsId.intValue());
        if (!textScanResult) {
            log.warn("文字审核失败");
            return;
        }
        // 5.调用图片审核接口
        Map map1 = greenImageScan.imageScan(imageList);
        Boolean imageScanResult = checkResult(map1, null, newsId.intValue());
        if (!imageScanResult) {
            log.warn("图片审核失败");
            return;
        }
        // 6.远程调用ArticleClient接口保存文章
        ArticleDto articleDto = wmNews2ArticleDto(wmNews);
        ResponseResult responseResult = iArticleClient.saveArticle(articleDto);
        if (responseResult == null || responseResult.getCode() != 200) {
            log.warn("文章保存失败");
            return;
        }
        Object data = responseResult.getData();
        Long articleId = (Long) responseResult.getData();
        // 7.将articleId回写到emNews表中
        updateWmNews(9, "审核通过", articleId, newsId.intValue());
    }

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    //DFA算法解决敏感字问题
    private Boolean dfaCheck(String text) {
        if (StringUtils.isBlank(text)) {
            return true;
        }
        //调用敏感词mapper，查询出所有的敏感词
        QueryWrapper<WmSensitive> wrapper = new QueryWrapper<>();
        wrapper.select("sensitives");
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(wmSensitives)) {
            return true;
        }

        List<String> words = wmSensitives.stream().filter(Objects::nonNull).map(WmSensitive::getSensitives).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(words)) {
            return true;
        }
        //DFA初始化
        SensitiveWordUtil.initMap(words);
        //DFA敏感词匹配
        Map<String, Integer> result = SensitiveWordUtil.matchWords(text);
        //判断结果   如果匹配结果为空那就通过   不为空会返回false
        return CollectionUtils.isEmpty(result);
    }

    /**
     * 接受图片，提取文字
     *
     * @param images
     * @return
     */
    private String ocrCheck(List<byte[]> images) throws IOException, TesseractException {
        if (CollectionUtils.isEmpty(images)) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (byte[] image : images) {
            //调用ocr提取文字
            //将图片转成流
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(image);
            //读取图片转换的流
            BufferedImage read = ImageIO.read(byteArrayInputStream);
            String text = OcrUtil.doOcr(read);
            //将每一次读取的文字添加进stringBuilder
            stringBuilder.append("_").append(text);
        }
        return stringBuilder.toString();
    }

    //处理入参
    private ArticleDto wmNews2ArticleDto(WmNews wmNews) {
        if (wmNews == null) {
            return null;
        }
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, articleDto);

        articleDto.setLayout(wmNews.getType());
        Integer channelId = wmNews.getChannelId();
        String channelName = null;
        //查询渠道名
        if (channelId != null) {
            WmChannel channel = wmChannelService.getById(channelId);
            channelName = articleDto.getChannelName();
            if (channelName != null) {
                articleDto.setChannelName(channelName);
            }
        }
        Integer userId = wmNews.getUserId();
        if (userId != null) {
            WmUser wmUser = wmUserService.getById(userId);
            if (wmNews != null) {
                articleDto.setAuthorName(wmUser.getName());
            }
        }
        return articleDto;
    }

    //更新news状态
    private Boolean updateWmNews(Integer status, String reason, Long articleId, Integer newsId) {
        WmNews wmNews = new WmNews();
        wmNews.setId(newsId);
        wmNews.setStatus(status.shortValue());
        wmNews.setReason(reason);
        if (articleId != null) {
            wmNews.setArticleId(articleId);
        }
        return wmNewsService.updateById(wmNews);
    }

    //处理审核结果
    private Boolean checkResult(Map result, Long articleId, Integer newsId) {
        if (CollectionUtils.isEmpty(result)) {
            log.warn("审核结果为空");
            return true;
        }
        String suggestion = (String) result.get("suggestion");
        if ("pass".equals(suggestion)) {
            return true;
        } else if ("block".equals(suggestion)) {
            //发布失败，更新文章状态
            updateWmNews(2, "未通过", articleId, newsId);
            return false;
        } else if ("review".equals(suggestion)) {
            updateWmNews(3, "人工审核", articleId, newsId);
            return false;
        }
        return true;
    }

    //提取文字的方法
    private String getText(String title, String content) {
        if (StringUtils.isBlank(content)) {
            return title;
        }
        List<Map> list = JSON.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(list)) {
            return title;
        }
        //单线程场景StringBuilder性能更高
        StringBuilder stringBuilder = new StringBuilder();
        for (Map map : list) {
            if (CollectionUtils.isEmpty(map)) {
                continue;
            }
            Object type = map.get("type");
            if ("text".equals(type)) {
                //读取文字内容
                String value = (String) map.get("value");
                stringBuilder.append(value);
            }
        }
        stringBuilder.append("_").append(title);
        return stringBuilder.toString();
    }

    //提取新闻图片
    private List<byte[]> getImages(String images, String content) {
        //声明一个集合用来存放获取到的图片
        List<String> finalList = new ArrayList<>();
        //获取封面图片
        if (StringUtils.isNotEmpty(images)) {
            String[] split = images.split(",");
            if (ArrayUtils.isNotEmpty(split)) {
                //将String数组转换成集合
                List<String> list = Arrays.asList(split);
                //添加到大集合
                finalList.addAll(list);
            }
        }
        //获取内容图片
        if (StringUtils.isNotBlank(content)) {
            List<Map> maps = JSON.parseArray(content, Map.class);
            if (!CollectionUtils.isEmpty(maps)) {
                for (Map map : maps) {
                    if (CollectionUtils.isEmpty(map)) {
                        continue;
                    }
                    Object type = map.get("type");
                    if ("image".equals(type)) {
                        String value = (String) map.get("value");
                        finalList.add(value);
                    }
                }
            }
        }
        //声明一个集合作为返回的结果
        List<byte[]> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(finalList)) {
            //遍历images和content提取组合出来的大集合
            for (String s : finalList) {
                if (StringUtils.isEmpty(s)) {
                    continue;
                }
                byte[] bytes = minIoTemplate.downLoadFile(s);
                //将转换之后的结果存入返回结果
                result.add(bytes);
            }
        }
        return result;
    }
}
